#include "stdafx.h"
#include "Strutil.h"
#include "MarketData.h"

MarketData::MarketData()
{
	instrument_id[0] = "IF1502";
	instrument_id[1] = "IF1503";
	is_both_received = false;
	_clear_his_data();
}

void MarketData::_clear_his_data()
{
	cur_tick_data[0].his_volume.clear();
	cur_tick_data[0].his_turnover.clear();
	cur_tick_data[1].his_volume.clear();
	cur_tick_data[1].his_turnover.clear();

	cur_tick_data[0].his_volume.push_back(0);
	cur_tick_data[0].his_turnover.push_back(0.0);
	cur_tick_data[1].his_volume.push_back(0);
	cur_tick_data[1].his_turnover.push_back(0.0);
}

bool MarketData::_is_in_market_time(const string &datetime)
{
	string time = datetime.substr(9, 5);
	if (time >= "09:15" && time <= "11:30" || time >= "13:00" && time <= "15:15")
	{
		return true;
	}
	return false;
}

void MarketData::update(char *line)
{
	int i;
	vector<char*> cols = split(line, ',');
	for (i = 0; i < 2; ++i)
	{
		if (instrument_id[i] == cols[2])
		{
			break;
		}
	}
	if (i >= 2 || !_is_in_market_time(cols[1]))
	{
		_clear_his_data();
		return;
	}

	cur_tick_data[i].receive_time = cols[0];
	cur_tick_data[i].update_time = cols[1];
	sscanf(cols[15], "%lf", &cur_tick_data[i].bid_price1);
	sscanf(cols[16], "%d", &cur_tick_data[i].bid_volume1);
	sscanf(cols[17], "%lf", &cur_tick_data[i].ask_price1);
	sscanf(cols[18], "%d", &cur_tick_data[i].ask_volume1);
	int volume = 0;
	sscanf(cols[10], "%d", &volume);
	cur_tick_data[i].his_volume.push_back(volume);
	double turnover = 0.0;
	sscanf(cols[11], "%lf", &turnover);
	cur_tick_data[i].his_turnover.push_back(turnover);
	
	int n = cur_tick_data[i].his_volume.size();
	if (n > 600)
	{
		cur_tick_data[i].avg_5min_price = (cur_tick_data[i].his_turnover[n - 1] - cur_tick_data[i].his_turnover[n - 601]) / (cur_tick_data[i].his_volume[n - 1] - cur_tick_data[i].his_volume[n - 601]) / 300.0;
	}
	else
	{
		cur_tick_data[i].avg_5min_price = -1.0;
	}

	if (cur_tick_data[i].update_time == cur_tick_data[1 - i].update_time)
	{
		is_both_received = true;
		buy_sell_diff = cur_tick_data[0].bid_price1 - cur_tick_data[1].ask_price1;
		sell_buy_diff = cur_tick_data[0].ask_price1 - cur_tick_data[1].bid_price1;
	}
	else
	{
		is_both_received = false;
	}
}